﻿using System;
using System.ComponentModel;

namespace CodeContrib
{
	public static class EnumExtensions
	{
		public static bool IsValidEnumValue<TEnum>(this string value) where TEnum : struct
		{
			try
			{
				return Enum.Parse(typeof (TEnum), value) != null;
			}
			catch
			{
				return false;
			}
		}

		public static string ToDescription(this Enum @enum)
		{
			var type = @enum.GetType();

			var memberInfo = type.GetMember(@enum.ToString());

			if (memberInfo != null
			    && memberInfo.Length > 0)
			{
				var attributes = memberInfo[0].GetCustomAttributes(typeof (DescriptionAttribute), false);

				if (attributes != null
				    && attributes.Length > 0)
				{
					return ((DescriptionAttribute)attributes[0]).Description;
				}
			}

			return @enum.ToString();
		}

		public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct
		{
			return (TEnum)Enum.Parse(typeof (TEnum), value);
		}
	}
}